import Vue from 'vue'
import VueRouter from 'vue-router'
import cookie from 'cookie'
Vue.use(VueRouter)

const routes = [
  {
    path:'/',redirect:'/home'
  },
  {
    path:'/card',name:'CCard',component:()=>import("../components/card.vue")
  },
  {
    path:'/personData',name:'PersonData',component:()=>import("../views/PersonData.vue"),
    meta: {
      requireAuth: true,  // 添加该字段，表示进入这个路由是需要登录的
    },
  },
  {
    path:'/manage',name:'Manage',component:()=>import("../views/ManageQuestionnaire.vue"),
    meta: {
      requireAuth: true,  // 添加该字段，表示进入这个路由是需要登录的
    },
  },
  {
    path: '/home',
    name: 'Home',
    component: ()=>import('../views/Home.vue')
  },
  {
    path: '/greeter',
    name: 'Greeter',
    component: () => import(/* webpackChunkName: "greeter" */ '../views/Greeter.vue')
  },
  {
    path: '/about',
    name: 'About',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
  },
  {
    path:'/login',
    name:'Login',
    component:()=>import('../views/Login.vue')
  },
  {
    path:'/register',
    name:'Register',
    component:()=>import('../views/Register.vue')
  },
  {
    path:'/edit',
    name:'Edit',
    component:()=>import('../views/Edit.vue'),
    meta: {
      requireAuth: true,  // 添加该字段，表示进入这个路由是需要登录的
    },
  },
  {
    path:'/edit/:id',
    name:'Edit',
    component:()=>import('../views/Edit.vue')
  },
  {
    path:'/share/:id',
    name:'Share',
    component:()=>import('../views/Share.vue')
  },
  {
    path:'/fill/:id',
    name:'Fill',
    component:()=>import('../views/Fill.vue')
  },
  {
    path:'/thanks',
    name:'Thanks',
    component:()=>import('../views/Thanks.vue')
  },
  {
    path:'/statistics',
    name:'Statistics',
    component:()=>import('../views/Statistics.vue'),
    meta: {
      requireAuth: true,  // 添加该字段，表示进入这个路由是需要登录的
    }
  },
  {
    path:'/answers',
    name:'Answers',
    component:()=>import('../views/Answers.vue')
  },
  {
    path:'/personalAnswer',
    name:'PersonalAnswer',
    component:()=>import('../views/PersonalAnswer.vue')
  },
  {
    path:'/examResult',
    name:'ExamResult',
    component:()=>import('../views/ExamResult.vue')
  },
  {
    path:'/voteResult',
    name:'VoteResult',
    component:()=>import('../views/VoteResult.vue')
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})
router.beforeEach((to, from, next) => {
  if (to.meta.requireAuth) {  // 判断该路由是否需要登录权限
    let isLogin=cookie.parse(document.cookie).isLogin
    if (isLogin) {  // 通过vuex state获取当前的token是否存在
      next();
    }
    else {
      next({
        path: '/login',
        query: {redirect: to.fullPath}  // 将跳转的路由path作为参数，登录成功后跳转到该路由
      })
    }
  }
  else {
    next();
  }
})
export default router
